#include <iostream>
#include <thread>
#include <mutex>
#include <string>

class Log {
public:
    Log() {};
    Log(const Log& log) = delete;
    Log& operator=(const Log& log) = delete;

    static Log& GetInstance() {
        // if (!log) log = new Log();  // 用多线程这里就会new两次，因此要使用call_once来确保只调用一次
        std::call_once(once, init);    // 加这个就只会new一次
        return *log;
    }

    static void init() {
        if (!log) log = new Log();
    }

    void PringError(std::string msg) {
        std::cout << __TIME__ << ": " << msg << std::endl;
    }
private:
    static Log* log;
    static std::once_flag once;     // 单次控制变量
};

void thread_func() {
    Log::GetInstance().PringError("error");
}

int main() {

    std::thread t1(thread_func);
    std::thread t2(thread_func);

    t1.join();
    t2.join();

    return 0;
}

Log* Log::log = nullptr;
std::once_flag Log::once;